<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<p>在线支付</p>
		</header>

		<!-- 订单信息部分 -->
		<h3>订单信息：</h3>
		<div class="order-info">
			<p>
				{{ orders.business.businessName }}
				<i class="fa fa-caret-down" @click="toggleDetailet"></i>
			</p>
			<p>¥{{ discountedPrice }}</p>
		</div>

		<!-- 订单明细 -->
		<ul class="order-detailet" v-show="isShowDetailet">
			<li v-for="item in orders.list" :key="item.food.foodId">
				<p>{{ item.food.foodName }} x {{ item.quantity }}</p>
				<p>¥{{ (item.food.foodPrice * item.quantity).toFixed(2) }}</p>
			</li>
			<li>
				<p>配送费</p>
				<p>¥{{ orders.business.deliveryPrice.toFixed(2) }}</p>
			</li>
			<li v-if="selectedRedPacket">
				<p>红包抵扣</p>
				<p>-¥{{ selectedRedPacket.num.toFixed(2) }}</p>
			</li>
		</ul>

		<!-- 选择红包 -->
		<h3>选择红包：</h3>
		<ul class="redpacket-list">
		    <li v-for="packet in redPackets" :key="packet.packetId" @click="applyRedPacket(packet)">
		        <p>{{ packet.num.toFixed(2) }} 元</p>
		        <p v-if="packet.deleted === 1" style="color: red;">已使用</p>
		        <p v-else-if="packet.packetId === selectedRedPacket?.packetId" style="color: green;">使用中</p>
		    </li>
		</ul>


		<!-- 支付方式部分 -->
		<h3>选择支付方式：</h3>
		<ul class="payment-type">
			<li @click="selectPaymentMethod('wallet')">
				<i class="fa fa-check-circle" v-if="selectedPayment === 'wallet'"></i>
				<p>钱包支付</p>
			</li>
			<li @click="selectPaymentMethod('alipay')">
				<img src="../assets/alipay.png">
				<i class="fa fa-check-circle" v-if="selectedPayment === 'alipay'"></i>
				<p>支付宝</p>
			</li>
			<li @click="selectPaymentMethod('wechat')">
				<img src="../assets/wechat.png">
				<i class="fa fa-check-circle" v-if="selectedPayment === 'wechat'"></i>
				<p>微信支付</p>
			</li>
		</ul>

		<!-- 确认支付按钮 -->
		<div class="payment-button">
			<button @click="confirmPayment">确认支付</button>
		</div>
	</div>
</template>

<script>
export default {
	name: 'Payment',
	data() {
		return {
			orderId: this.$route.query.orderId,
			user:{},
			orders: {
				business: {deliveryPrice: 0},
				list: [],
				orderTotal: 0
			},
			redPackets: [],
			selectedRedPacket: null,
			selectedPayment: 'wallet',
			isShowDetailet: false,
			walletId: null,
			orderState: 1,
			balance:0
		};
	},
	computed: {
		// 计算最终支付价格（原价 - 红包抵扣）
		discountedPrice() {
			const originalPrice = (this.orders.orderTotal || 0) + (this.orders.business.deliveryPrice || 0);
			const finalPrice = this.selectedRedPacket ? originalPrice - this.selectedRedPacket.num : originalPrice;
			return finalPrice.toFixed(2);
		}
	},
	created() {
		this.user = this.$getSessionStorage('user') || {}; // 确保 this.user 不为空
		// 获取订单信息
		this.$axios.get('/Orders/OrdersId', {
			params: { orderId: this.orderId }
		}).then(response => {
			this.orders = response.data.result;
		}).catch(error => {
			console.error("获取订单信息失败:", error);
		});

		this.$axios.get('/RedPacket/userId',{
				params: {
					userId: this.user.userId,
				}
			})
			.then(response => {
				this.redPackets = response.data.result.filter(packet => packet.deleted === 0);
			}).catch(error => {
				console.error("获取订单信息失败:", error);
			});
		this.$axios.get('VirtualWallet/UserId',{
				params: {
					userId: this.user.userId,
				}
			})
			.then(response => {
				this.balance = response.data.result.balance ;
				this.walletId = response.data.result.walletId;
			}).catch(error => {
				console.error("获取订单信息失败:", error);
			});
	},
	methods: {
		// 展开订单明细
		toggleDetailet() {
			this.isShowDetailet = !this.isShowDetailet;
		},

		// 选择支付方式
		selectPaymentMethod(method) {
			this.selectedPayment = method;
		},

		// 选择红包
		applyRedPacket(packet) {
			if (packet.deleted ===0) {
				this.selectedRedPacket = packet;
			}
		},

		// 确认支付
		async confirmPayment() {
		    const amount = parseFloat(this.discountedPrice);
		if (this.selectedPayment === 'wallet') {
				        if (this.balance < amount) {
				            alert('余额不足，请选择其他支付方式');
				            return; // 终止支付流程
				        }
				    }
		    try {
		        // 获取钱包ID
		
		        // 钱包支付
		        if (this.selectedPayment === 'wallet') {
		            await this.$axios.post('VirtualWallet/FromWalletId', 
		                this.$qs.stringify({
		                    amount: amount,
		                    walletId: this.walletId
		                })
		            );
		        }
		
		        // 使用红包（如果选中了）
		        if (this.selectedRedPacket) {
		            await this.$axios.post(`/RedPacket/PacketId`, this.$qs.stringify({
		                packetId: this.selectedRedPacket.packetId
		            }));
		        }
		
		        // 给予用户积分
		        await this.$axios.post(`/Credit/userId`, this.$qs.stringify({
		            userId: this.user.userId,
		            num: Math.floor(amount),
		            channelType: 1
		         
		        }));
		
		        // 更新订单状态
		        await this.$axios.put('Orders/OrdersId', this.$qs.stringify({
		            orderId: this.orderId,
		            orderState: this.orderState
		        }));
		
		        // 跳转到支付成功页面
		        this.$router.push({ path: '/paymentresult' });
		
		    } catch (error) {
		        console.error('支付过程中发生错误:', error);
		        alert(`支付失败: ${error.message}`);
		    }
		}

	}
};
</script>




<style scoped>
/****************** 总容器 ******************/
.wrapper {
	width: 100%;
	height: 100%;
}

/****************** header部分 ******************/
.wrapper header {
	width: 100%;
	height: 12vw;
	background-color: #0097FF;
	color: #fff;
	font-size: 4.8vw;
	position: fixed;
	left: 0;
	top: 0;
	z-index: 1000;
	display: flex;
	justify-content: center;
	align-items: center;
}

/****************** 订单信息部分 ******************/
.wrapper h3 {
	margin-top: 12vw;
	box-sizing: border-box;
	padding: 4vw 4vw 0;
	font-size: 4vw;
	font-weight: 300;
	color: #999;
}

.wrapper .order-info {
	box-sizing: border-box;
	padding: 4vw;
	font-size: 4vw;
	color: #666;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.wrapper .order-info p:last-child {
	color: orangered;
}

/****************** 订单明细部分 ******************/
.wrapper .order-detailet {
	width: 100%;
}

.wrapper .order-detailet li {
	width: 100%;
	box-sizing: border-box;
	padding: 1vw 4vw;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.wrapper .order-detailet li p {
	font-size: 3vw;
	color: #666;
}

/****************** 红包选择部分 ******************/
.wrapper .redpacket-list {
	width: 100%;
}

.wrapper .redpacket-list li {
	width: 100%;
	box-sizing: border-box;
	padding: 2vw 4vw;
	display: flex;
	justify-content: space-between;
	align-items: center;
	cursor: pointer;
}

.wrapper .redpacket-list li p {
	font-size: 3.5vw;
	color: #666;
}

.wrapper .redpacket-list li:hover {
	background-color: #f5f5f5;
}

/****************** 支付方式部分 ******************/
.wrapper .payment-type {
	width: 100%;
}

.wrapper .payment-type li {
	width: 100%;
	box-sizing: border-box;
	padding: 4vw;
	display: flex;
	justify-content: space-between;
	align-items: center;
	cursor: pointer;
}

.wrapper .payment-type li img {
	width: 33vw;
	height: 8.9vw;
}

.wrapper .payment-type li .fa-check-circle {
	font-size: 5vw;
	color: #38CA73;
}

/****************** 支付按钮 ******************/
.wrapper .payment-button {
	width: 100%;
	box-sizing: border-box;
	padding: 4vw;
}

.wrapper .payment-button button {
	width: 100%;
	height: 10vw;
	border: none;
	/* 去掉外轮廓线 */
	outline: none;
	border-radius: 4px;
	background-color: #38CA73;
	color: #fff;
	font-size: 4vw;
}

</style>

